<?php
namespace app\admin\controller;

use app\common\model\Gamelist as 	GamelistModel;
use app\common\model\Gameagent as 	GameagentModel;
use app\common\controller\AdminBase;
use think\Config;
use think\Db;
use app\common\model\Channel;

/**
 * 代理管理
 * Class AdminUser
 * @package app\admin\controller
 * @author ys
 */
class GameAgent extends AdminBase
{
	protected $gameagent_model;
    protected $gamelist_model;
    protected function initialize()
    {
        parent::initialize();
		$this->gameagent_model = new GameagentModel();
		$this->gamelist_model = new GamelistModel();
    }

    /**
     * 代理管理
     * @param string $keyword
     * @param int    $page
     * @return mixed
	 * @author ys
     */
    public function index()
    {
        $map = [];
        $data = input();
        $page = $data['page'] ?? 1;
        $map[] =['a.cid','<>',5];
        if(isset($data['cid']) && $data['cid'] != ""){
            $map[] =['a.cid','=',$data['cid']];
        }
        $keyword = "";
        if(!empty($data['keyword'])){
            $keyword = $data['keyword'];
            $map[] = ['b.name', 'like', "%{$keyword}%"];
        }
        
        $gameagent = GameagentModel::alias('a')
            ->join('gamelist b', 'a.gid = b.id', 'left')
            ->where($map)
            ->field('a.*, b.name as game_name')
            ->order('a.id DESC')
            ->paginate(15, false, ['page' => $page,'query' =>request()->param()]);

        return $this->fetch('index', ['gameagent' => $gameagent, 'keyword'=>$keyword]);
    }
	
    /**
     * 添加代理
     * @return mixed
	 * @author ys
     */
    public function add()
    {
        return $this->fetch();
    }
	
    /**
     * 生成接口key
     */
    public function addkey()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
			if ($data['type'] == 'loginkey'){
				$newkey = md5(sha1(session_id() . time()). Config::get('lsalt'));
				$result = [
				            'code'   => 1,
							'msg' => $newkey
				];
			}elseif ($data['type'] == 'paykey'){
				$newkey = md5(sha1(session_id() . time()). Config::get('psalt'));
				$result = [
				           'code'   => 1,
				           'msg' => $newkey
				];
			}
			return json($result);
        }
    }
	
    /**
     * 保存代理
	 * @author ys
     */
    public function save()
    {
        if ($this->request->isPost()) {
            $data            = $this->request->post();
            $validate_result = $this->validate($data, 'GameAgent');
            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
                $gameagent = GameagentModel::where(['gid'=>$data['gid'],'cid'=>$data['cid']])->find();
                if($gameagent){
                    $this->error('已存在请勿重复添加');
                }
                $game = GamelistModel::where(['id'=>$data['gid']])->find();
                $channel = Channel::where(['id'=>$data['cid']])->find();
                if($channel->fee <= 0){
                    $this->error('请设置渠道分成比例');
                }
                $data['applytime']= time();
                $data['login_url']= $_SERVER['HTTP_ORIGIN']."/game/play/".$data['gid'].'/'.$data['cid'];
                if($data['cid'] != 5){
                    $data['login_url']= $_SERVER['HTTP_ORIGIN']."/aiqiH5/play/".$data['gid'].'/'.$data['cid'];
                }
                if($data['cid'] == 15){
                    $data['login_url']= $_SERVER['HTTP_ORIGIN']."/aiqiH5/register/".$data['gid'].'/'.$data['cid'];
                }
                if (GameagentModel::insert($data)) {
                    $this->success('保存成功','/admin/agent');
                } else {
                    $this->error('保存失败');
                }
            }
        }
    }
	
    /**
     * 编辑代理
     * @param $id
     * @return mixed
	 * @author ys
     */
    public function edit($id)
    {
		$gameagent = GameagentModel::find($id);
        return $this->fetch('edit', ['gameagent' => $gameagent]);
    }

    /**
     * 更新代理
     * @param $id
	 * @author ys
     */
    public function update($id)
    {
        if ($this->request->isPost()) {
            $data            = $this->request->post();
            $validate_result = $this->validate($data, 'GameAgent');
            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
                if (GameagentModel::where('id',$id)->update($data)) {
                    $this->success('更新成功','/admin/agent');
                } else {
                    $this->error('更新失败');
                }
            }
        }
    }
	
    /**
     * 更改状态
     * @param $id
	 * @author ys
     */
    public function check($id,$type,$status)
    {
        if ($this->request->isPost()) {
			$game               = $this->garea_model->find($id);
			$game->id           = $id;
			if ($type == 'show'){
			$game->show         = $status;
			}elseif($type == 'status'){
			$game->status       = $status;	
			}
            if ($game->save() !== false) {
                $this->success('更新状态成功');
            } else {
                $this->error('更新状态成功');
            }
        }
    }	

	public function getkey()
	{
		$data=[];
		if ($this->request->isget()) {
			$data['username']= input('get.username');	
			$data['key']=md5(time().rand(100000, 999999).$data['username']);
		}
		return json($data);
	}


    public function extData($id){
        $agent = new GameagentModel();
        $extData = $agent->find($id);

        $this->assign('gameagent',$extData);
        $data = [];
        if(!empty($extData['extdata'])){
            $data = json_decode($extData['extdata'],true);

            $this->assign('data',$data);
            return $this->fetch('ext_data');
        }else{
            return $this->fetch('set_data');
        }

    }

    /**
     * 更新代理
     * @param $id
     * @author ys
     */
    public function saveData($id)
    {
        if ($this->request->isPost()) {
            $data            = json_encode($this->request->post());
            if (GameagentModel::where('id',$id)->update(['extdata'=>$data])) {
                $this->success('更新成功','/admin/agent');
            } else {
                $this->error('更新失败');
            }
        }
    }

    /**
     * 高德代理管理
     * @param string $keyword
     * @param int    $page
     * @return mixed
     * @author ys
     */
    public function gaode()
    {
        $map = [];
        $data = input();
        $page = $data['page'] ?? 1;

        $map[] =['a.cid','=',5];

        $keyword = "";
        if(!empty($data['keyword'])){
            $keyword = $data['keyword'];
            $map[] = ['b.name', 'like', "%{$keyword}%"];
        }

        $gameagent = GameagentModel::alias('a')
            ->join('gamelist b', 'a.gid = b.id', 'left')
            ->where($map)
            ->field('a.*, b.name as game_name')
            ->order('a.id DESC')
            ->paginate(15, false, ['page' => $page,'query' =>request()->param()]);

        return $this->fetch('gaode', ['gameagent' => $gameagent, 'keyword'=>$keyword]);
    }

    /**
     * 添加代理
     * @return mixed
     * @author ys
     */
    public function gaode_add()
    {
        return $this->fetch();
    }

    /**
     * 保存代理
     * @author ys
     */
    public function gaode_save()
    {
        if ($this->request->isPost()) {
            $data            = $this->request->post();
            $validate_result = $this->validate($data, 'GameAgent');
            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
                $gameagent = GameagentModel::where(['gid'=>$data['gid'],'cid'=>$data['cid']])->find();
                if($gameagent){
                    $this->error('已存在请勿重复添加');
                }
                $game = GamelistModel::where(['id'=>$data['gid']])->find();
                $channel = Channel::where(['id'=>$data['cid']])->find();
                if($channel->fee <= 0){
                    $this->error('请设置渠道分成比例');
                }
                $data['applytime']= time();
                $data['login_url']= $_SERVER['HTTP_ORIGIN']."/game/play/".$data['gid'].'/'.$data['cid'];
                if($data['cid'] != 5){
                    $data['login_url']= $_SERVER['HTTP_ORIGIN']."/aiqiH5/play/".$data['gid'].'/'.$data['cid'];
                }
                if (GameagentModel::insert($data)) {
                    $this->success('保存成功','/admin/agent');
                } else {
                    $this->error('保存失败');
                }
            }
        }
    }

    /**
     * 编辑代理
     * @param $id
     * @return mixed
     * @author ys
     */
    public function gaode_edit($id)
    {
        $gameagent = GameagentModel::find($id);
        return $this->fetch('gaode_edit', ['gameagent' => $gameagent]);
    }

    /**
     * 更新代理
     * @param $id
     * @author ys
     */
    public function gaode_update($id)
    {
        if ($this->request->isPost()) {
            $data            = $this->request->post();
            $validate_result = $this->validate($data, 'GameAgent');
            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
                if (GameagentModel::where('id',$id)->update($data)) {
                    $this->success('更新成功','/admin/agent_gaode');
                } else {
                    $this->error('更新失败');
                }
            }
        }
    }

}